<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use View;
use App\Model\Permission;

class PermissionController extends AdminBaseController
{
    public function __construct()
    {
        $option = ['module_name'=>'permission','status'=>'permission_status'];
        $this->setModelObj(new Permission,$option);
    }
    /**
	 * 更新权限表
	 */
	public function permissionRefresh()
	{
        $survived_data = [];$add_data = [];
		$db_data = Permission::get()->toArray();
		foreach (glob(base_path('routes') . '/admin/*.php') as $file){
			preg_match_all("/(\w)*Controller@(\w)*/", file_get_contents($file), $preg);
            if($preg){
                foreach($preg[0] as $val){
                    $arr_tmp = explode('@',$val);
                    $data = [
                         'controller_name' => $arr_tmp[0],
                         'action_name' => $arr_tmp[1],
                    ];
                    $data_status = $this->getSearchData($data,$db_data);
                    //判断是否是数据库数据，若是，保留主键id，若不是，保存文件数据
                    if($data_status){
                        $survived_data[] = $data_status;
                        unset($data);
                    }else{
                        $data['controller_action'] = $data['controller_name'].'@'.$data['action_name'];
                        $add_data[] = $data;
                    }
                }
            }
		}
		Permission::whereNotIn('permission_id',$survived_data)->delete();
        $re = Permission::insert($add_data);

        $jsonData = $re ? $this->getJsonData(1,'变更成功') : $this->getJsonData(0,'变更失败');
        return response()->json($jsonData);
	}
	
	/**
	 * 数据筛选函数
	 * parammer search_data 筛选数据
	 * parammer db_data  总数据
	 */
	protected function getSearchData($search_data,$db_data)
	{
		$result = 0;
        if($db_data){
            foreach($db_data as $k => $data){
                //获取两个数组交集
                $intersect = array_intersect_assoc($search_data,$data);
                //若交集完全等于查询数组，则为包含关系，即符合查询条件
                if($intersect == $search_data){
                    $result = $data['permission_id'];
                }
            }
        }
		return $result;
	}

    /**
     * 修改权限名称
     */
    protected function toEditNameData(Request $request)
    {
        $id = $request->get('id');
        $re = Permission::where('permission_id',$id)->update(['permission_name'=>$request->get('content')]);
        $jsonData = $re ? $this->getJsonData(1,'编辑成功') : $this->getJsonData(0,'编辑失败');
        return response()->json($jsonData);
    }
}